package cn.rxls.community.strategy.bill.impl;

import cn.rxls.community.entity.billEntity.BillOthers;
import cn.rxls.community.dto.bill.AddBillDTO;
import cn.rxls.community.entity.Bill;
import cn.rxls.community.enums.BillStateEnum;
import cn.rxls.community.enums.BillTypeEnum;
import cn.rxls.community.enums.ResultEnum;
import cn.rxls.community.exception.BusinessException;
import cn.rxls.community.mapper.BillMapper;
import cn.rxls.community.strategy.bill.BillStrategy;
import cn.rxls.community.strategy.bill.BillStrategyFactory;
import cn.rxls.community.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;

/**
 * 其他账单策略实现
 */
@Service("BilOthersStrategy")
@Transactional
public class BilOthersStrategyImpl implements BillStrategy {
    private final BillMapper billMapper;

    BilOthersStrategyImpl(BillMapper billMapper) {
        this.billMapper = billMapper;

    }


    /**
     * 根据类型添加账单
     *
     * @param dto 参数对象
     * @return 是否成功
     */
    @Override
    public Boolean addBill(AddBillDTO dto) {

        //用户id
        String uid = String.valueOf(HttpUtil.getUserLoginInfo().get("uid"));

        Bill bill = new Bill();
        BeanUtils.copyProperties(dto,bill);
        bill.setBillUser(Long.valueOf(uid));
        bill.setBillState(BillStateEnum.WARN_PAY.code);

        //反序列化成对象，再序列化成json字符串，过滤除对象外的其他字段
        try {
            BillOthers billOthers = JSON.parseObject(dto.getBillSpecifics(), BillOthers.class);
            bill.setBillSpecifics(JSON.toJSONString(billOthers));
        } catch (Exception e) {
            throw new BusinessException(ResultEnum.ERROR_JSON_BILL);
        }

        return billMapper.insert(bill) > 0;
    }

    /**
     * json字符串序列化为对象
     *
     * @param jsonStr json字符串
     * @return json对象
     */
    @Override
    public Object jsonString(String jsonStr) {
        return JSON.parseObject(jsonStr, BillOthers.class);
    }


    /**
     * bean初始化完以后，将添加策略实现到maq中
     */
    @PostConstruct
    public void initStrategy() {
        BillStrategyFactory.register(BillTypeEnum.OTHERS.msg, this);
    }
}
